<!-- 异常完结 -->
<template>
	<view class="contact">
		<view class="head-context">
			<div class="head-info">
				<p><span class="head-number" style="position: relative;top: -5px;">单号</span><span class="number" disabled>{{items.waybillNumber}}</span></p>
				<p><span style="letter-spacing:1px;position: relative;top: -10px;">操作人</span><input type="text" class="number" style="background-color: #ebebeb;margin-left: 28px;margin-top: 10px;" v-model="signer" placeholder="操作人"></input></p>
				<p><span style="letter-spacing:1px;position: relative;top: -10px;">签收证件</span><input type="text" class="number" style="background-color: #ebebeb;" v-model="signingDocument" placeholder="签收证件号"></input></p>
				<p><span style="letter-spacing:7px;position: relative;top: -10px;">核销号</span><input type="text" class="number" disabled></input></p>
				<p><span style="margin-left: 50px;">
					<checkbox-group @change="checkboxChange">
			        <label class="checkbox-item" style="display: inline-block;">
			            <checkbox value="true" checked="true" class="checkbox-checked" @change="toggleRememberMe" :checked="rememberMe">是否核销</checkbox>
			            
			        </label>
					</checkbox-group>
			    </span></p>
			</div>
		</view>
		<view class="reason-context">
		</view>
		<view class="photo-context">
			<p class="photo-text" style="display: flex; align-items: center;">
			    拍照
			    <span class="sum" style="position: relative;left: 290px;">{{images.length}}/5</span>
			</p>
				<view v-for="(image, index) in images" :key="index" class="image-item" >
				      <image :src="image" style="width: 80px; height: 80px;"></image>
				    </view>
			<span class="photo" v-if="images.length<5"><img src="../../../static/相机.png" class="photo-icon" @click="chooseImages">
			</span>
		</view>
		<view class="end" >
			<button class="end-button" @click="addClick">保存</button>
		</view>
	</view>
</template>

<script>
	import {getDetails} from '@/api/sign.js';
	import {completed} from '@/api/abnormal.js';
	export default {
		data() {
			return {
				  images: [] ,// 存储选中的图片路径,
				  items:{},
				  signer:'',//签收人姓名
				  signingDocument:'',//签收人证件
				  req:{
				  },
				  // fileList:[],
				  picture:[],//存储后的路径
				  pictureString:'',
				  imageUrl:'',
				  id:0
				  
			}
		},
		onLoad(options) {
					this.businessId=options.businessId
					this.phone=options.phone
					this.id=options.id
			},
		mounted(){
			getDetails({businessId: this.businessId}).then(res =>{
				this.items=res.data.data
			}).catch((error) => {
			});
		},
		methods: {
			addClick(){
				const that = this;
				if(this.images.length<3){
					uni.showToast({
					        title: '至少需要上传三张照片！',
					        icon: 'none',
					    });
					 return; // 如果为空，则不执行后续操作
				}
				 if (!this.signer) {
						uni.showToast({
						        title: '请填写证件人',
						        icon: 'none',
						    });
				        return; // 如果为空，则不执行后续操作
				}
				this.req.id=this.id
				this.req.signer=this.signer
				this.req.signingDocument=this.signingDocument
				this.req.signingTime=new Date();
				this.req.completed=this.picture.toString();
				console.log(this.req)
				completed(this.req).then(res =>{
					this.visible = false;
					this.$emit('add-item', 1);
					if(res.data.status===400){
						 uni.showToast({
						     title: res.data.errorMessage,
						     icon: 'none',
						 });
						 return;
					}
				uni.showToast({
					        title: '完结成功',
					        icon: 'success',
					    });
				uni.navigateBack({
				  delta: 1 // 可选，默认为1，表示返回上一页面
				});
				}).catch((error) => {
				    // 请求失败
				    console.error('完结失败', error);
				    uni.showToast({
				        title: '完结失败，请重试',
				        icon: 'none',
				    });
				});
			},
			
			chooseImages() {
			      uni.chooseImage({
			        count: 9, // 允许选择图片的数量，默认为9
			        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
			        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
			        success: (res) => {
						 // 获取新选择的图片路径
						const newImages = res.tempFilePaths;
						this.images = this.images.concat(res.tempFilePaths);
						// 遍历新选择的图片，并检查是否已上传或已选择
						newImages.forEach((filePath) => {
			          // 将选中的图片路径添加到images
					    this.uploadFile(filePath);
					  });
			        },
					
			      });
				  
			    },
				uploadFile(filePath) {
				      uni.uploadFile({
				        url: 'https://image.ff5630.com/upload/buy/upload', // 仅为示例，非真实的接口地址
				        filePath: filePath,
				        name: 'file',
				        formData: {
				          user: 'test'
				        },
				        success: (uploadFileRes) => { // 使用箭头函数来保持this的上下文
						try {
						          // 解析服务器返回的JSON响应
						          const responseObj = JSON.parse(uploadFileRes.data);
						          const uploadedImageUrl = responseObj.data; // 假设服务器返回的是图片的URL
						 
						          // 检查并添加URL到picture数组（避免重复）
						          const completeUrl = uploadedImageUrl.startsWith('http://') || uploadedImageUrl.startsWith('https://')
						            ? uploadedImageUrl
						            : 'https://' + uploadedImageUrl; // 根据实际情况调整URL格式
						 
						          if (!this.picture.includes(completeUrl)) {
						            this.picture.push(completeUrl);
						          }
								  console.log(this.picture)
						          console.log('上传成功，图片URL：', completeUrl);
						 
						          // 其他处理上传成功后的逻辑可以在这里添加
						 
						        } catch (error) {
						          console.error('解析上传响应失败：', error);
						        }
						  // const urlStr=uploadFileRes.data;
						  // const startIndex = urlStr.indexOf('"data":"') + '"data":"'.length; // 找到"data":"并跳过它
						  // const endIndex = urlStr.indexOf('"', startIndex); // 找到从startIndex开始的第一个"
						   
						  //  const rawImageUrl = urlStr.substring(startIndex, endIndex);
						    
						  //  // 检查URL是否已经是完整的（以http://或https://开头）
						  //  if (!rawImageUrl.startsWith('http://') && !rawImageUrl.startsWith('https://')) {
						  //    this.imageUrl = 'https://' + rawImageUrl;
						  //  } else {
						  //    this.imageUrl = rawImageUrl;
						  //  }
						  // if (!this.picture.includes(this.imageUrl)) {
						  //      this.picture.push(this.imageUrl);
						  //  }
						  //  console.log(this.imageUrl)
						  //  console.log(this.picture)
						  // 提取URL=
				          // 处理上传成功后的逻辑
				        },
				        fail(err) {
				          console.error('上传失败：', err);
				        }
				      });
					  }
		}
	}
</script>

<style>
@import "pictureToast.css";
</style>
